package test;

import lombok.Getter;
import lombok.Setter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws InterruptedException {
//        test1();
        test3();
    }

    private static void test3(){
        String LD = "LD";
        int LX = 1;
        int num = 1;
        String format1 = String.format("%02d", LX);
        String format2 = String.format("%06d", num);
        System.out.println(LD + format1 + format2);
    }

    private static void test2() throws InterruptedException {
        int k = 5;

        CountDownLatch latch = new CountDownLatch(k);//两个线程并行

        for (int i = 0; i < k; i++) {
            Worker worker = new Worker(5000, latch, " ");
            worker.setIndex(i);
            worker.start();
        }

        latch.await();//等待所有工人完成工作点
        System.out.println("all work done at " + sdf.format(new Date()));
    }

    private static void test1() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);//两个线程并行
        Worker worker1 = new Worker(5000, latch, " 1 ");
        Worker worker2 = new Worker(8000, latch, " 2 ");
        worker1.start();//
        worker2.start();//
        latch.await();//等待所有工人完成工作点

        System.out.println("all work done at " + sdf.format(new Date()));
    }

    static class Worker extends Thread {
        String workerName;
        int workTime;
        CountDownLatch latch;
        @Getter
        @Setter
        int index;

        public Worker(int workTime, CountDownLatch latch, String workerName) {
            this.workerName = workerName;
            this.workTime = workTime;
            this.latch = latch;
        }

        public void run() {
            System.out.println("Worker " + workerName + " do work begin at " + sdf.format(new Date()));
            doWork();//工作了
            System.out.println("Worker " + workerName + " do work complete at " + sdf.format(new Date()));
            latch.countDown();//工人完成工作，计数器减一

        }

        private void doWork() {
            try {
                Thread.sleep(workTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
